package app.biz.service.impl;

import app.biz.service.atom.CodeMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;

/** ECG-XK代码映射 */
@Service
public class XKCodeMapperImpl implements CodeMapper {
  private static final Logger logger = LoggerFactory.getLogger(XKCodeMapperImpl.class);
  Properties mapping;

  public static  final String RESULT_FIELD_NAME  = "xk_code";

  @Bean
  int loadEcgXK() throws IOException {
    mapping = PropertiesLoaderUtils.loadAllProperties("ecg-xk.properties");
    return 0;
  }

  private String mapCode(int ecgCode) {
    if (mapping.get(String.valueOf(ecgCode))!= null) {
      return mapping.get(String.valueOf(ecgCode)).toString();
    }
    //如果找不到对应的业务代码则返回空字符串
    return "";
  }

    @Override
    public String mapCode(Object[] ecgCode) {
      final String[] xkCode = {""};
    Arrays.asList(ecgCode)
        .forEach(
            n -> {
              String mappedCode = mapCode((Integer) n);
              if (!Strings.isNullOrEmpty(mappedCode)) {
                xkCode[0] = xkCode[0].concat(mapCode((Integer) n) + ",");
              }
//              logger.info("ecgCode:{},xkCode:{}", n, mapCode((Integer) n));
            });
      if(xkCode[0].length()<2){
        return "";
      }
      //去掉末尾多余分隔符(,)
      return xkCode[0].substring(0, xkCode[0].length()-1);
    }

  /**
   * 为原始结果添加熙康代码
   * @param resultObj */
  @Override
  public void addCode(JSONObject resultObj) {
    Object[] ecgCodeArr = resultObj.getJSONObject("result").getJSONArray("symptom_code").toArray();
    String mappedCode = mapCode(ecgCodeArr);
    JSONArray arr = new JSONArray();
    //无任何熙康代码对应则将空数组加入结果集
    if(Strings.isNullOrEmpty(mappedCode)){
      resultObj.getJSONObject("result").put(RESULT_FIELD_NAME,arr);
      return;
    }
    Arrays.asList(mappedCode.split(",")).forEach(s -> {
      arr.add(Integer.valueOf(s));
    });
    resultObj.getJSONObject("result").put(RESULT_FIELD_NAME,arr);
  }
}
